package com.arron.juc;

/**
 * @Classname NotSafeDemo
 * @Description TODO
 * @Date 2020/8/19 20:54
 * @Created by 刘
 */

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 集合类list,set,map线程不安全问题
 * 1.出现的异常
 *  java.util.ConcurrentModificationException 并发修改异常
 * 2.原因
 *  多个线程再同时读和写，导致一个线程在写时另一个线程再读或者也在写
 * 3.解决方案
 *  1）使用 Vector ,底层加了 synchronized
 *  2)使用 Collections.synchronizedList(new ArrayList<>()); 底层使用 synchronized (mutex) 同步锁代码块
 *  3)使用 new CopyOnWriteArrayList<>(), 采用写时复制技术，底层加了ReentrantLock lock锁，使用了Arrys.copyof()扩容，写完后在释放锁
 */

public class NotSafeDemo {

    public static void main(String[] args) {

//        setNotSafeDemo();
        Map<String, String> strs =new HashMap<>();
        Map<String, String> strs2 =new ConcurrentHashMap<>();

    }

    private static void setNotSafeDemo() {
        Set<String> strs = new CopyOnWriteArraySet<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                strs.add(UUID.randomUUID().toString().replace("-","").substring(0,5));
                System.out.println(strs);
            }, String.valueOf(i)).start();
        }
    }

    private static void listNotSafeDemo() {
        List<String> strs = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                strs.add(UUID.randomUUID().toString().replace("-","").substring(0,5));
                System.out.println(strs);
            }, String.valueOf(i)).start();
        }
    }

}
